package com.jfinal.web.controller;

import com.jfinal.exception.BusinessException;
import com.jfinal.plugin.activerecord.Model;

public abstract class CrudController<M extends Model<M>> extends DefaultController<M> {

    /**
     * 添加
     */
    public void add() {
        M model = getModel();
        try {
            if (!beforeAdd( model )) {
                return;
            }
            if (service.save( model )) {
                renderSuccess( "添加成功!" );
            } else {
                renderFailed( "添加失败!" );
            }
        } catch (BusinessException e) {
            renderFailed( "添加异常:" + e.getMessage() );
        }
        return;
    }

    /**
     * 保存对象之前
     *
     * @param model
     */
    protected boolean beforeAdd(M model) {
        return true;
    }

    /**
     * 编辑
     */
    public void edit() {
        try {
            M model = getModel();
            if (!beforeEdit( model )) {
                return;
            }
            if (service.update( model )) {
                renderSuccess( "更新成功!" );
            } else {
                renderFailed( "更新失败!" );
            }
        } catch (BusinessException e) {
            renderFailed( "更新异常:" + e.getMessage() );
        }
        return;
    }

    /**
     * 更新对象之前
     *
     * @param model
     */
    protected boolean beforeEdit(M model) {
        return true;
    }


    /**
     * 删除
     */
    public void delete() {
        M model = getModel();
        try {
            if (!beforeDelete( model )) {
                return;
            }
            if (service.delete( model )) {
                renderSuccess( "删除成功!" );
            } else {
                renderFailed( "删除失败!" );
            }
        } catch (BusinessException e) {
            renderFailed( "删除异常:" + e.getMessage() );
        }
    }

    /**
     * 更新对象之前
     *
     * @param model
     */
    protected boolean beforeDelete(M model) {
        return true;
    }


}
